﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MarginTrading.Entity;
using MarginTrading.Common;
using MarginTrading.Services;
using System.IO;

namespace MarginTrading.Forms
{
    public partial class InitialSettlements : Form
    {
        double fBuyTotal = 0;
        int iCheckedRow = -1;
        bool bTableDrawn = false;

        string sCurrentAgentCode = "";
        string sCurrentBrokerCode = "";

        public InitialSettlements()
        {
            InitializeComponent();
        }

        private void InitialSettlements_Load(object sender, EventArgs e)
        {
            try
            {
                Config config = ConfigServices.GetConfigByName(Constants.CONFIG_NAME_DEPLOYMENT_SIDE);

                if (config.Value == Constants.CONFIG_VALUE_DEPLOYMENT_SIDE_BROKER)
                {
                    AgentCollection agentCollection = AgentServices.GetAgentCollection();

                    for (int iI = 0; iI < agentCollection.Count; iI++)
                    {
                        comboBoxAgentCode.Items.Add(agentCollection[iI].Code);
                    }

                    config = ConfigServices.GetConfigByName(Constants.CONFIG_NAME_COMPANY_CODE);
                    comboBoxBrokerCode.Items.Add(config.Value);
                    comboBoxBrokerCode.SelectedIndex = 0;
                    comboBoxAgentCode.SelectedIndex = 0;

                    labelBuyTotal.Text = "0";
                }
                else if (config.Value == Constants.CONFIG_VALUE_DEPLOYMENT_SIDE_AGENT)
                {
                    BrokerCollection brokerCollection = BrokerServices.GetBrokerCollection();

                    for (int iI = 0; iI < brokerCollection.Count; iI++)
                    {
                        comboBoxBrokerCode.Items.Add(brokerCollection[iI].Code);
                    }

                    config = ConfigServices.GetConfigByName(Constants.CONFIG_NAME_COMPANY_CODE);
                    comboBoxAgentCode.Items.Add(config.Value);
                    comboBoxAgentCode.SelectedIndex = 0;
                    comboBoxBrokerCode.SelectedIndex = 0;
                }
            }
            catch (System.Exception ex)
            {

            }

            WindowState = FormWindowState.Maximized;
        }

        private void buttonGO_Click(object sender, EventArgs e)
        {
            int iCount = dataGridViewBuy.Columns.Count;
            for (int iI = 0; iI < iCount; iI++)
            {
                dataGridViewBuy.Columns.RemoveAt(0);
            }

            //DataGridViewCheckBoxColumn Chk1 = new DataGridViewCheckBoxColumn();
            //Chk1.HeaderText = "Select";
            //Chk1.Name = "Chk1";
            //dataGridViewBuy.Columns.Add(Chk1);
            //dataGridViewBuy.Columns["Chk1"].DisplayIndex = 0;

            sCurrentAgentCode = comboBoxAgentCode.Text;
            sCurrentBrokerCode = comboBoxBrokerCode.Text;

            try
            {
                dataGridViewBuy.DataSource = DailyTransactionsServices.GetInitialSettlementDataTable(comboBoxBrokerCode.Text, comboBoxAgentCode.Text);
            }
            catch (System.Exception ex)
            {

            }

            for (int iI = 0; iI < dataGridViewBuy.Columns.Count; iI++)
            {
                dataGridViewBuy.Columns[iI].SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            dataGridViewBuy.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight;

            bTableDrawn = true;

            fBuyTotal = 0;
            labelBuyTotal.Text = "0.00";

            for (int iI = 0; iI < dataGridViewBuy.Rows.Count; iI++)
            {
                fBuyTotal += double.Parse(dataGridViewBuy.Rows[iI].Cells[3].Value.ToString());
                labelBuyTotal.Text = String.Format("{0:0.00}", fBuyTotal); //fBuyTotal.ToString();
            }

            textBoxSettleAmount.Text = dataGridViewBuy.SelectedRows[0].Cells[3].Value.ToString();

            InitialSettlements_SizeChanged(null, null);
        }

        private void InitialSettlements_SizeChanged(object sender, EventArgs e)
        {
            dataGridViewBuy.Width = (Size.Width - 75);
            dataGridViewBuy.Height = Size.Height - 170;
            dataGridViewBuy.Left = 20;

            int iClearance = 80;
            labelBuyTotal.Top = Height - iClearance;
            labelTotal1.Top = Height - iClearance;
            buttonBuySettle.Top = Height - iClearance - 2;
            textBoxSettleAmount.Top = Height - iClearance - 2;
            labelAmount.Top = Height - iClearance;
            labelBuyTotal.Left = dataGridViewBuy.Left + 60;
            labelTotal1.Left = dataGridViewBuy.Left;
            labelAmount.Left = dataGridViewBuy.Left + 165;
            textBoxSettleAmount.Left = labelAmount.Right + 15;
            buttonBuySettle.Left = textBoxSettleAmount.Right + 20;

            if (bTableDrawn)
            {
                //dataGridViewBuy.Columns[0].Width = 0;
                dataGridViewBuy.Columns[0].Width = 150;
                dataGridViewBuy.Columns[2].Width = 200;
                dataGridViewBuy.Columns[3].Width = 150;

                dataGridViewBuy.Columns[1].Width = dataGridViewBuy.Width -
                    (500
                    //+ dataGridViewBuy.Columns[2].Width
                    //+ dataGridViewBuy.Columns[3].Width
                    + 2);
            }
        }

        private void dataGridViewBuy_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            textBoxSettleAmount.Text = dataGridViewBuy.SelectedRows[0].Cells[3].Value.ToString();

            //if (dataGridViewBuy.CurrentCell.ColumnIndex != 0)
            //{
            //    return;
            //}

            //if (dataGridViewBuy.CurrentCell.Value == null
            //    || (bool)dataGridViewBuy.CurrentCell.Value == false)
            //{
            //    if (iCheckedRow != -1)
            //    {
            //        dataGridViewBuy.Rows[iCheckedRow].Cells[0].Value = false;
            //    }
            //    iCheckedRow = dataGridViewBuy.CurrentRow.Index;
            //    dataGridViewBuy.CurrentCell.Value = true;
            //}
            //else
            //{
            //    dataGridViewBuy.CurrentCell.Value = false;
            //    iCheckedRow = -1;
            //}
        }

        private void buttonBuySettle_Click(object sender, EventArgs e)
        {
            if (ValidateInputs() == false)
            {
                return;
            }

            string sClientCode = dataGridViewBuy.SelectedRows[0].Cells[0].Value.ToString();
            double dInitAccBal = double.Parse(dataGridViewBuy.SelectedRows[0].Cells[3].Value.ToString());
            double dAmount = double.Parse(textBoxSettleAmount.Text);
            dInitAccBal -= dAmount;
            try
            {
                DailyTransactionsServices.AddInitialAccBal(sClientCode, dInitAccBal, false);

                LoanAccount accountEntry = new LoanAccount();

                string sReferenceNO = GetReferenceCode("PA");
                accountEntry.Amount = dAmount;
                accountEntry.ReferenceNo = sReferenceNO;
                accountEntry.ClientCode = sClientCode;
                accountEntry.CreatedDate = DateTime.Today;
                accountEntry.EntryType = "PA";
                accountEntry.TrParticulars = "Payment on Purchases"; //Ravin1
                accountEntry.Remarks = "Payment on Purchases"; //Ravin1

                LoanAccountServices.Add(accountEntry);

            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Settlement failed. Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            comboBoxAgentCode.Text = sCurrentAgentCode;
            comboBoxBrokerCode.Text = sCurrentBrokerCode;
            buttonGO_Click(null, null);
            MessageBox.Show("Settlement successful");
        }

        private bool ValidateInputs()
        {
            if (textBoxSettleAmount.Text == "")
            {
                MessageBox.Show("Enter amount to settle", "Amount empty", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            double amount = 0;
            if (double.TryParse(textBoxSettleAmount.Text, out amount) == false)
            {
                MessageBox.Show("The amount you entered is not valid", "Invalid amount", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            double dInitAccBal = double.Parse(dataGridViewBuy.SelectedRows[0].Cells[3].Value.ToString());
            if (amount > dInitAccBal)
            {
                MessageBox.Show("The amount you entered is higher than the initial account balance of the client" +
                    Environment.NewLine + "Amount should be less than or equal to the initial account balance of the client",
                    "Invalid amount", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return false;
            }

            return true;
        }

        private string GetReferenceCode(string sType)
        {
            return sType + "-" + Program.GetNextSeqNO().ToString();
        }
    }
}
